package com.skypan.mqtt_csdn;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.HashMap;


public class MainActivity extends AppCompatActivity {

    MqttAndroidClient mqttAndroidClient;

    /**
     * 设置mqtt服务器地址、客户端ID、主题等
     */

    final String serverUri = "";//mqtt服务器地址
    String clientId = "";//客户端ID
    final String subscriptionTopic = "";//主题


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        clientId = clientId + System.currentTimeMillis();//客户端ID防重复

        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {//连接完成

            }

            @Override
            public void connectionLost(Throwable cause) {//连接失去
                Log.i("connectionLost","连接失去");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message)  {//信息到达 ！！！
                makeToast(new String(message.getPayload()));
//                publishMessage();
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {//推送完成

            }
        });

        //连接设置
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName("");//用户名
        mqttConnectOptions.setPassword("".toCharArray());//密码
        mqttConnectOptions.setAutomaticReconnect(true);//重连
        mqttConnectOptions.setCleanSession(false);//清空Session

        try {
            //addToHistory("Connecting to " + serverUri);
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    makeToast("连接成功！");
                    subscribeToTopic();//订阅主题
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.i("exception",exception.toString());
                    makeToast("错误！连接失败！" + exception);
                }
            });


        } catch (MqttException ex){
            ex.printStackTrace();
        }
        Button btn = findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               
                publishMessage();
            }
        });

    }

    public void subscribeToTopic(){
        try {
            mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    makeToast("成功订阅到" + subscriptionTopic);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    makeToast("订阅失败" + subscriptionTopic);

                }
            });



        } catch (MqttException ex){
    
            ex.printStackTrace();
        }
    }    public void publishMessage(){

        try {
            MqttMessage message = new MqttMessage();
            String publishMessage = "return";
            message.setPayload(publishMessage.getBytes());
            String publishTopic = "public";
            mqttAndroidClient.publish(publishTopic, message);
            if(!mqttAndroidClient.isConnected()){
            }
        } catch (MqttException e) {
           
            e.printStackTrace();
        }
    }

    private void makeToast(String str){
        Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();

    }

}
